package com.yunji.generate.util;

import com.yunji.generate.bean.ColumnInfo;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hushuang
 * @since 2019/9/20
 */
public class TypeMappingUtil {

    /**
     * 基础类型转包装类型
     */
    private static final Map<Class<?>, Class<?>> SIMPLE_TO_WRAPPER_MAPPINGS;

    /**
     * 类型替换
     */
    private static final Map<String, String> JAVA_TYPE_REPLACE_MAPPINGS;

    static {
        SIMPLE_TO_WRAPPER_MAPPINGS = new HashMap<>();

        SIMPLE_TO_WRAPPER_MAPPINGS.put(boolean.class, Boolean.class);
        SIMPLE_TO_WRAPPER_MAPPINGS.put(byte.class, Byte.class);
        SIMPLE_TO_WRAPPER_MAPPINGS.put(char.class, Character.class);
        SIMPLE_TO_WRAPPER_MAPPINGS.put(double.class, Double.class);
        SIMPLE_TO_WRAPPER_MAPPINGS.put(float.class, Float.class);
        SIMPLE_TO_WRAPPER_MAPPINGS.put(int.class, Integer.class);
        SIMPLE_TO_WRAPPER_MAPPINGS.put(long.class, Long.class);
        SIMPLE_TO_WRAPPER_MAPPINGS.put(short.class, Short.class);

        JAVA_TYPE_REPLACE_MAPPINGS = new HashMap<>();

        JAVA_TYPE_REPLACE_MAPPINGS.put(Timestamp.class.getName(), Date.class.getName());
        JAVA_TYPE_REPLACE_MAPPINGS.put(Boolean.class.getName(), Integer.class.getName());
    }

    public static Class<?> simpleToWrapper(Class<?> simpleType) {
        return SIMPLE_TO_WRAPPER_MAPPINGS.getOrDefault(simpleType, simpleType);
    }

    public static boolean isBoolean(Class<?> type) {
        return boolean.class.equals(type) || Boolean.class.equals(type);
    }

    public static String getJavaType(ColumnInfo columnInfo) {
        // 特殊处理整数类型
        if ("NUMBER".equals(columnInfo.getTypeName()) && columnInfo.getDecimalDigits() == 0) {
            if (columnInfo.getColumnSize() <= 10) {
                return Integer.class.getName();
            }
            return Long.class.getName();
        }
        return JAVA_TYPE_REPLACE_MAPPINGS.getOrDefault(columnInfo.getColumnClassName(), columnInfo.getColumnClassName());
    }
}
